<template>
  <div ref="chartRef" :style="{ height }"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';
import { useChartDataFetch } from '../composables/useChartDataFetch';

interface ChartDataItem {
  name: string;
  value: number;
}

interface ChartData {
  dataSource: {
    type: 'static' | 'api' | 'sql';
    data?: string;
    url?: string;
    method?: string;
    params?: string;
    sql?: string;
  };
  config: Record<string, any>;
}

const props = defineProps({
  chartData: {
    type: Object as () => ChartData,
    required: true
  },
  height: {
    type: String,
    default: '100%'
  }
});

const chartRef = ref<HTMLElement>();
let chart: echarts.ECharts | null = null;

// 获取图表数据
const { data, startFetch } = useChartDataFetch(props.chartData.dataSource);

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;
  
  chart = echarts.init(chartRef.value);
  
  // 监听容器大小变化
  const resizeObserver = new ResizeObserver(() => {
    chart?.resize();
  });
  resizeObserver.observe(chartRef.value);
  
  // 清理
  onUnmounted(() => {
    resizeObserver.disconnect();
    chart?.dispose();
  });
};

// 更新图表
const updateChart = () => {
  if (!chart || !data.value) return;
  
  const option = {
    grid: {
      top: 40,
      right: 20,
      bottom: 40,
      left: 60,
      containLabel: true
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: data.value.map(item => item.name),
      axisLine: {
        lineStyle: {
          color: 'rgba(255,255,255,0.3)'
        }
      },
      axisLabel: {
        color: '#fff'
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: 'rgba(255,255,255,0.3)'
        }
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255,255,255,0.1)'
        }
      },
      axisLabel: {
        color: '#fff'
      }
    },
    series: [{
      data: data.value.map(item => item.value),
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 8,
      lineStyle: {
        width: 3
      },
      itemStyle: {
        color: '#409EFF'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
          offset: 0,
          color: 'rgba(64,158,255,0.3)'
        }, {
          offset: 1,
          color: 'rgba(64,158,255,0)'
        }])
      }
    }],
    ...props.chartData.config
  };
  
  chart.setOption(option);
};

// 初始化
onMounted(() => {
  initChart();
  startFetch();
});

// 监听数据变化
watch(data, () => {
  updateChart();
}, { deep: true });
</script> 